import React, { useState, useEffect, useMemo, useRef } from 'react';
import { router, withRouter } from 'umi';
import { Card, Button, Collapse, Icon, Table, Switch, Select, message, Spin } from 'antd';
import { useRequest } from '@/hooks';
import FunctionDescribe from '@/components/NewFunction/FunctionDescribe';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction, GuideByServerFlag } from '@/components';
import { replaceTreeNode, removeEmptyChildren, effectSubNode, effectParentNode } from '@/utils/tree';
import { fetchManageList } from '@/pages/Setting/Privilege/services';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import LabelValue from '@/pages/Setting/Privilege/components/LabelValue';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import ButtonConfirm from '@/pages/Setting/Privilege/components/ButtonConfirm';
import { isEqual } from 'lodash';
import { TreeSelectGroup } from '../../components/TreeSelectGroupRoleForPrivilege';
import {
    getNewFunctionDetail,
    newFunctionSaveHiData,
    newFunctionDeployDraft,
    getNewFunctionDeployDraft,
    setNewFunctionRead
} from '../../services';
import { filterSoftwarePlatform, depthLookupSort } from '../utils';
import { FUNCTION_TYPE, ORGANIZATIONAL_SCOPE, ADMINISTRATIVE_SCOPE, FUNCTION_GRADE } from '../constants';
import styles from '../index.less';

const NewFunctionDeploy = ({ location }) => {
    const [enable, setEnable] = useState(false);
    const [detail, setDetail] = useState({});
    const [dataSource, setDataSource] = useState([]);
    const [canAction, setCanAction] = useState(false);
    const { userCode } = JSON.parse(localStorage.getItem('user') || '{}');
    const guideRef = useRef();

    const { query } = location;
    const { resourceCode, auditStatus } = query;

    const { data: manageList } = useRequest(fetchManageList);

    const { run: fetchNewFunctionRead } = useRequest(params => setNewFunctionRead(params), {
        manual: true
    });

    const { run: fetchNewFunctionDetail, loading: loadingDetail } = useRequest(params => getNewFunctionDetail(params), {
        manual: true,
        onSuccess: ({ msg, code, data }) => {
            if (code === 10000) {
                const { auditStatus: status } = data;
                const isDisabled = status === 1 || status === 2;
                fetchNewFunctionRead({ resourceCode: data.code, userCode });
                setCanAction(isDisabled);
                setDetail(data);
            } else {
                message.error(msg);
            }
        }
    });

    const { run: fetchNewFunctionDetailTree, loading: loadingTree } = useRequest(
        params => getNewFunctionDeployDraft(params),
        {
            manual: true,
            onSuccess: ({ msg, code, data }) => {
                if (code === 10000) {
                    const { tenantResourceNewFunctionVO, isEnable } = data;
                    const result = removeEmptyChildren([tenantResourceNewFunctionVO]);
                    setEnable(isEnable);
                    // 如果已经启用了不做指引
                    if (isEnable === false) {
                        guideRef.current.start();
                    }
                    setDataSource(result);
                } else {
                    message.error(msg);
                }
            }
        }
    );

    const { run: fetchNewFunctionSaveHiData, loading: loadingFlow } = useRequest(
        params => newFunctionSaveHiData(params),
        {
            manual: true
        }
    );

    const { run: fetchNewFunctionDeployDraft, loading: loadingDraft } = useRequest(
        params => newFunctionDeployDraft(params),
        {
            manual: true
        }
    );

    const isLoading = useMemo(() => loadingDetail || loadingTree || loadingFlow || loadingDraft, [
        loadingDetail,
        loadingDraft,
        loadingFlow,
        loadingTree
    ]);

    useEffect(() => {
        fetchNewFunctionDetail({ resourceCode });
        fetchNewFunctionDetailTree({ resourceCode, auditStatus });
    }, [auditStatus, fetchNewFunctionDetail, fetchNewFunctionDetailTree, resourceCode]);

    const handleRowDataChange = record => {
        const { code } = record;
        const result = replaceTreeNode(dataSource, 'code', code, record);
        setDataSource(result);
    };

    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            width: 300
        },
        {
            title: '类型',
            dataIndex: 'type',
            width: 150,
            render: value => <span>{FUNCTION_TYPE[value]}</span>
        },
        {
            title: '状态',
            width: 150,
            dataIndex: 'isEnable',
            render: (value, record) => (
                <div className={styles.functionStatusWrapper}>
                    {typeof value === 'boolean' ? (
                        <Switch
                            disabled={canAction || record.code === detail.code}
                            onChange={isEnable => {
                                let effectResult = dataSource;
                                if (isEnable) {
                                    effectResult = effectParentNode(effectResult, 'code', record.code, {
                                        isEnable
                                    });
                                }
                                effectResult = effectSubNode(effectResult, 'code', record.code, { isEnable });

                                setDataSource(effectResult);
                            }}
                            checked={value}
                        />
                    ) : (
                        <span>-</span>
                    )}
                </div>
            )
        },
        {
            title: '等级',
            dataIndex: 'functionGrade',
            width: 200,
            render: (value, record) => (
                <Select
                    disabled={canAction}
                    value={typeof value === 'number' ? value : undefined}
                    style={{ width: 100 }}
                    onChange={rank => {
                        const result = { ...record, functionGrade: rank };
                        handleRowDataChange(result);
                    }}
                >
                    <Select.Option value={1}>基础</Select.Option>
                    <Select.Option value={2}>职能</Select.Option>
                    <Select.Option value={3}>高级</Select.Option>
                </Select>
            )
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>业务端实现情况</div>
                    <ul>
                        <li>Web端</li>
                        <li>APP端</li>
                        <li>PC端</li>
                    </ul>
                </div>
            ),
            dataIndex: 'terminalScope',
            width: 200,
            render: (value = {}) => {
                const { WEB, APP, PC } = value;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        {WEB ? <Icon type="check" /> : <span>-</span>}
                        {APP ? <Icon type="check" /> : <span>-</span>}
                        {PC ? <Icon type="check" /> : <span>-</span>}
                    </div>
                );
            }
        },
        {
            title: '授权模板',
            dataIndex: 'roleCodes',
            render: (value, record) => (
                <TreeSelectGroup
                    disabled={canAction}
                    data={manageList?.data || []}
                    value={value}
                    onChange={template => {
                        const result = { ...record, roleCodes: template };
                        handleRowDataChange(result);
                    }}
                />
            )
        }
    ];

    // 连接至流程
    const goToWorkFlow = async (workFlowUrl, code) => {
        history.push(`${workFlowUrl}${code}`);
    };

    /**
     * 保存
     */
    const handleStorage = async (showMsg = true) => {
        try {
            const { msg, code } = await fetchNewFunctionDeployDraft({
                resourceCode: detail.code,
                isEnable: enable,
                tenantResourceNewFunctionVO: dataSource[0]
            });

            if (showMsg) {
                if (code === 10000) {
                    message.success('保存成功');
                } else {
                    message.error(msg);
                }
            }
        } catch {
            message.error('获取用户信息失败');
        }
    };

    // 判断流程是否存在
    const handleApproval = async () => {
        const { workFlowUrl } = await hasWorkFlowByType('NewFunctionApply');
        if (workFlowUrl) {
            const { code, msg, data } = await fetchNewFunctionSaveHiData({
                resourceCode: detail.code,
                userCode,
                isEnable: enable,
                tenantResourceNewFunctionVO: dataSource[0]
            });
            if (code === 10000) {
                await handleStorage(false);
                goToWorkFlow(workFlowUrl, data);
            } else {
                message.error(msg);
            }
        }
    };

    /**
     * 下一步
     */
    const handleNextSubmit = async () => {
        handleApproval();
    };

    const handleEnable = value => {
        setEnable(value);
        const result = effectSubNode(dataSource, 'code', detail.code, { isEnable: value });
        setDataSource(result);
        guideRef.current.stop();
    };

    return (
        <PageHeaderWrapper>
            <GuideByServerFlag ref={guideRef} serverStorageKey="guideNewFunctionDeploy">
                <Spin spinning={isLoading}>
                    <Card
                        bordered={false}
                        className={styles.newFunctionWrapper}
                        extra={
                            !canAction && (
                                <BottomAction>
                                    <CancelEditConfirm>
                                        <Button>取消</Button>
                                    </CancelEditConfirm>
                                    <ButtonConfirm
                                        confirmVisible={async () => {
                                            const { code, data, msg } = await getNewFunctionDeployDraft({
                                                resourceCode,
                                                auditStatus
                                            });
                                            if (code === 10000) {
                                                const { tenantResourceNewFunctionVO, isEnable } = data;
                                                const result = removeEmptyChildren([tenantResourceNewFunctionVO]);
                                                const OriginNewFunctionsValue = depthLookupSort(result, 'roleCodes');
                                                const LocalNewFunctionsValue = depthLookupSort(dataSource, 'roleCodes');

                                                const confirm = isEqual(
                                                    { isEnable, newFunctions: OriginNewFunctionsValue },
                                                    { isEnable: enable, newFunctions: LocalNewFunctionsValue }
                                                );

                                                return Promise.resolve(confirm);
                                            }
                                            return Promise.reject(msg);
                                        }}
                                        onConfirm={handleStorage}
                                    >
                                        <Button type="primary" ghost disabled={!detail.code} loading={isLoading}>
                                            保存
                                        </Button>
                                    </ButtonConfirm>
                                    <Button
                                        type="primary"
                                        disabled={!detail.code}
                                        loading={isLoading}
                                        onClick={handleNextSubmit}
                                    >
                                        下一步
                                    </Button>
                                </BottomAction>
                            )
                        }
                    >
                        <header className={styles.pageHeader}>
                            <h2>新功能详情</h2>
                        </header>
                        <FunctionDescribe
                            title={detail.nameZh}
                            describe={detail.onlineRemarkZh}
                            releaseTime={detail.onlineTime}
                        />
                        <Collapse
                            className={styles.collapsePanel}
                            bordered={false}
                            expandIconPosition="right"
                            defaultActiveKey={['newFunctionDeployTree']}
                            expandIcon={panelProps => {
                                const { isActive } = panelProps;
                                return (
                                    <div className={styles.collapseExpandIcon}>
                                        {isActive ? '收起' : '展开'}
                                        {isActive ? <Icon type="caret-up" /> : <Icon type="caret-down" />}
                                    </div>
                                );
                            }}
                        >
                            <Collapse.Panel header="功能详情" key="newFunctionDeployDetail">
                                <div className={styles.functionDescribeList}>
                                    <LabelValue label="功能中文名称" value={detail.nameZh} />
                                    <LabelValue label="功能英文名称" value={detail.nameEn} />
                                    <LabelValue label="功能类型" value={FUNCTION_TYPE[detail.type]} />
                                    <LabelValue label="从属功能" value={detail.parentNameZh} />
                                    <LabelValue label="模块简介（中文）" value={detail.remarkZh} />
                                    <LabelValue label="模块简介（英文）" value={detail.remarkEn} />
                                    <LabelValue
                                        label="业务端实现情况"
                                        value={filterSoftwarePlatform(detail.terminalScope)}
                                    />
                                    <LabelValue label="初始等级" value={FUNCTION_GRADE[detail.functionGrade]} />
                                    {detail?.type === 1 && (
                                        <LabelValue
                                            label="初始数据权限"
                                            value={`行政机构：${ADMINISTRATIVE_SCOPE[
                                                detail.defaultAdministrativeScope
                                            ] || ''}<br />组织机构：${ORGANIZATIONAL_SCOPE[
                                                detail.defaultOrganizationalScope
                                            ] || ''}`}
                                        />
                                    )}
                                </div>
                            </Collapse.Panel>

                            <Collapse.Panel header="功能配置" key="newFunctionDeployTree">
                                <div className={styles.functionList}>
                                    <div className={styles.enableNewFunction}>
                                        <span>是否开启：</span>
                                        {!enable && (
                                            <GuideByServerFlag.Step
                                                placement="right"
                                                content={
                                                    <>
                                                        启用功能后，可进行权限配置
                                                        <br />
                                                        对不同子功能配置等级与授权模板
                                                    </>
                                                }
                                            >
                                                <span>
                                                    <Switch
                                                        checked={enable}
                                                        disabled={canAction}
                                                        onChange={handleEnable}
                                                    />
                                                </span>
                                            </GuideByServerFlag.Step>
                                        )}
                                        {enable && (
                                            <Switch checked={enable} disabled={canAction} onChange={handleEnable} />
                                        )}
                                    </div>
                                    {enable && (
                                        <>
                                            <div style={{ marginBottom: 10 }}>配置权限：</div>
                                            <Table
                                                className={styles.functionListTable}
                                                columns={columns}
                                                pagination={false}
                                                rowKey="code"
                                                dataSource={dataSource}
                                                expandIcon={({ expanded, onExpand, record }) => {
                                                    const { children } = record;
                                                    if (!children) {
                                                        return <span style={{ width: 14, height: 14 }}></span>;
                                                    }
                                                    return expanded ? (
                                                        <Icon
                                                            type="caret-down"
                                                            style={{ marginRight: 5 }}
                                                            onClick={e => onExpand(record, e)}
                                                        />
                                                    ) : (
                                                        <Icon
                                                            type="caret-right"
                                                            style={{ marginRight: 5 }}
                                                            onClick={e => onExpand(record, e)}
                                                        />
                                                    );
                                                }}
                                            />
                                        </>
                                    )}
                                </div>
                            </Collapse.Panel>
                        </Collapse>
                    </Card>
                </Spin>
            </GuideByServerFlag>
        </PageHeaderWrapper>
    );
};

export default withRouter(NewFunctionDeploy);
